<template>
    <div>
        <div id="audioRecord" class="center_div">  <!--隐藏html-->
            <!------------------------------------顶部查询栏-------------------------------->
            <div class="searchForm dataManage18px" style="margin-top: 1%;margin-left: 1%;">
                <el-form :inline="true" :model="searchForm" :label-position="label_position">

                    <el-form-item :label="searchForm.type.label">
                        <el-select v-model="searchForm.type.value" :placeholder="searchForm.type.placeholder||'请选择'"
                                   @change="changeCalledType"
                        >
                            <el-option
                                    v-for="item in searchForm.type.options"
                                    :key="item.ID"
                                    :label="item.NAME"
                                    :value="item.ID">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="searchForm.callerid.label">
                        <el-select v-model="searchForm.callerid.value"
                                   :placeholder="searchForm.callerid.placeholder||'请选择'"
                        >
                            <el-option
                                    v-for="item in searchForm.callerid.options"
                                    :key="item.ID"
                                    :label="item.NAME"
                                    :value="item.user_id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item :label="searchForm.calledid.label">
                        <el-select v-model="searchForm.calledid.value"
                                   :placeholder="searchForm.calledid.placeholder||'请选择'"
                        >
                            <el-option
                                    v-for="item in searchForm.calledid.options"
                                    :key="item.ID"
                                    :label="item.NAME"
                                    :value="item.ID">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="searchForm.starttime.label">

                        <el-date-picker v-model="searchForm.starttime.value" type="datetime" :editable="false"
                                        :picker-options="pickerOptionsStart" value-format="yyyy-MM-dd HH:mm:ss"
                                        style="width: 100%"
                                        placeholder="选择日期时间" @change="changeStart"></el-date-picker>
                    </el-form-item>
                    <el-form-item :label="searchForm.endtime.label">

                        <el-date-picker v-model="searchForm.endtime.value" type="datetime" :editable="false"
                                        :picker-options="pickerOptionsEnd" value-format="yyyy-MM-dd HH:mm:ss"
                                        style="width: 100%"
                                        placeholder="选择日期时间" @change="changeEnd"></el-date-picker>
                    </el-form-item>


                    <el-form-item>
                        <el-button class="dataManageBtn22BtnpPx" type="primary" @click="querySearch">查询
                        </el-button>
                    </el-form-item>
                    <!-- <el-form-item>
                       <el-button class="playBtn" type="primary">批量播放</el-button>
                     </el-form-item>
                     <el-form-item>
                       <el-button class="loadBtn" type="primary">批量下载</el-button>
                     </el-form-item>-->
                </el-form>
            </div>
            <!--显示最近记录-->
            <!----------------------------------中间表格栏---------------------------------->
            <div class="table-wrap" style="width: 98%;height: 70%">
                <el-table
                        fit
                        :data="tableData"
                        class="tableDataClass"
                        border
                        cell-class-name="dataManage18px"
                        :header-cell-style="headerCellClassName"
                >

                    <el-table-column align="center" v-for="title in tableTitle" :prop="title.prop" :label="title.label"
                                     :width="title.width">
                    </el-table-column>
                    <el-table-column
                            class="align-right"
                            width="320"
                            header-align="center"
                            label="操作"
                            align="center">
                        <template slot-scope="scope">
                            <el-button v-for="button in buttons" @click="deal(scope.row,button.value)"
                                       :type="button.type" size="medium" class="dataManageFooterBtnMargin">
                                {{button.label}}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!---------------------------------- 分页---------------------------------->
                <el-pagination
                        layout="total,prev, pager, next"
                        background
                        :current-page="pageNum"
                        :page-size="pageSize"
                        :total="total"
                        @current-change="changePageNum"
                        style="margin-bottom: 20px">
                </el-pagination>


            </div>
            <el-dialog
                    width="40%"
                    title="音频播放"
                    :visible.sync="showPlayer"
                    append-to-body>
                <div style="width: 100%">
                    <aplayer v-if="showPlayer" ref="videoPlayRef" :music="videoPlay" :autoplay="true"
                    ></aplayer>
                </div>
            </el-dialog>
        </div>

    </div>
</template>

<script>
  import DispatchVoiceApi from '@/api/DispatchVoiceApi';
  import AuditQuery from '@/api/dataManages//AuditQuery.js';
  import aplayer from 'vue-aplayer';

  export default {
    name: 'LogAuditManagement',
    props: {//父组件数据
      FleetId: Number,
      userId: Number,
      UserAccount: String,
    },
    components: {
      aplayer,
    },
    data() {
      return {
        label_position: 'right',
        dataforms: [],
        rowsforms: [],
        dialogRecent: false,
        showPlayer: false,
        videoPlay: {
          title: '音频',
          artist: '',
          src: '',
          pic: 'https://moeplayer.b0.upaiyun.com/aplayer/secretbase.jpg',
        },
        searchForm: {

          type: {
            label: '类型',
            value: '',
            type: 'select',
            prop: 'type',
            options: [{'ID': '0', 'NAME': '单呼'}, {'ID': '1', 'NAME': '组呼'}, {'ID': '', 'NAME': '全部'}],
          },
          callerid: {label: '主叫', value: '', type: 'select', prop: 'callerid', options: []},

          calledid: {label: '被叫', value: '', type: 'select', prop: 'calledid', options: []},
          starttime: {label: '开始时间', value: '', type: 'time', prop: 'starttime'},
          endtime: {label: '结束时间', value: '', type: 'time', prop: 'endtime'},
          groupOptions: [],
        },
        pickerOptionsStart: {},
        pickerOptionsEnd: {},
        tableTitle: [
          // {label: '序号', prop: 'index'},
          {label: '讲话方', prop: 'callername'},
          {label: '听方', prop: 'calledname'},
          {label: '开始时间', prop: 'starttime', width: '320px'},
          {label: '结束时间', prop: 'endtime', width: '350'},
          {label: '时长', prop: 'duration'},
        ],
        recentTableTitle: [
          // {label: '序号', prop: 'index'},
          {label: '主叫', prop: 'callername'},
          {label: '被叫', prop: 'calledname'},
          {label: '呼叫类型', prop: 'calltype'},
          {label: '开始时间', prop: 'starttime', width: 320},
          {label: '结束时间', prop: 'endtime', width: 320},
        ],
        buttons: [{label: '播放', value: 'play', type: 'primary'}, {label: '下载', value: 'dld', type: 'primary'}],
        tableData: [],   //搜索结果
        recentTableData: [],   //最近记录搜索结果
        typeMap: ['单呼', '组呼', '临时组呼', 'IP单呼', 'IP会议'],//呼叫类型Map
        total: 0,
        pageNum: 1,
        pageSize: 10,

        //对于dialog里当前正在播放的
        currentRow: null,
        //调度台绑定的话机信息
        TelephoneBind: {
          extnum: '',
          status: '',
          subId: '',
        },
      };
    },
    created() {
      this.changeDmgPage();
    },
    mounted() {
      this.queryUser();
      this.query(1);
    },
    methods: {
      querySearch() {
        this.query(1);
        this.pageNum = 1;
      },
      changeDmgPage() {
        let w = window.screen.width;
        let h = window.screen.height;
        if (w == 1920) {
          if (h == 1080) {
            this.pageSize = 7;
          } else {
            this.pageSize = 11;
          }
        }
      },
      changeCalledType(val) {
        console.info('%c changeCallerid=' + val, 'color:red');
        if (val === 1) {
          if (this.searchForm.groupOptions.length > 0) {
            this.searchForm.calledid.options = this.searchForm.groupOptions;
          } else {
            this.queryGroup();
          }
        }
      },
      headerCellClassName() {
        return 'font-size:18px;color:#515A6E;padding:10px 0px 10px 0px !important;background:#F5F5F6;border:1px solid #EBEBEB';
      },
      //表格样式
      cellStyleClassName() {
        return 'font-size:13px;text-align:center;color:#606266;padding:5px 0px 5px 0px !important;border:1px solid #EBEBEB';
      },
      changeStart() { // 限制开始时间

        this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
          disabledDate: (time) => {
            if (this.searchForm.starttime.value) {
              return time.getTime() < this.searchForm.starttime.value;
            }
          },
        });
      },

      changeEnd() { // 限制结束时间
        this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
          disabledDate: (time) => {
            if (this.searchForm.endtime.value) {
              return time.getTime() > (this.searchForm.endtime.value);
            }
          },
        });
      },
      // 将时间戳转为时分秒
      formatSeconds(value) {
        var theTime = parseInt(value);// 秒
        var theTime1 = 0;// 分
        var theTime2 = 0;// 小时
        if (theTime > 60) {
          theTime1 = parseInt(theTime / 60);
          theTime = parseInt(theTime % 60);
          if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
          }
        }
        var result = '' + parseInt(theTime) + '秒';
        result = '' + parseInt(theTime1) + '分' + result;
        result = '' + parseInt(theTime2) + '时' + result;
        return result;
      },
      query(pageNum) {
        this.pageNum = pageNum;
        var condition =
            {
              'callerid': this.searchForm.callerid.value,
              'starttime': this.searchForm.starttime.value,
              'endtime': this.searchForm.endtime.value,
              'pageIndex': this.pageNum,
              'pageSize': this.pageSize,
              'utype': this.searchForm.type.value,
              'logType': '2',
              'calledid': this.searchForm.calledid.value,
              'fid': this.$store.getters.scsFleetId,
              calleridLeftExt: '',//主叫 左话机号  存在不绑定情况
              calledidLeftExt: '',//被叫  左话机号
            };
        if (condition.starttime != '' && condition.starttime != null) {
          condition.starttime = this.GlobalFunc.GlaChangeDate(condition.starttime);
        }
        if (condition.endtime != '' && condition.endtime != null) {
          condition.endtime = this.GlobalFunc.GlaChangeDate(condition.endtime);
        }
        console.info(1, 'color:red');
        //TODO 主叫左话机号
        try {
          //主叫左话机号
          if (condition.callerid != '' && condition.callerid != null) {
            if (this.searchForm.callerid.options.length > 0) {
              for (let i = 0; i < this.searchForm.callerid.options.length; i++) {
                if (this.searchForm.callerid.options[i].user_id == condition.callerid) {
                  if (this.searchForm.calledid.options[i].leftExt != undefined) {
                    condition.calleridLeftExt = this.searchForm.callerid.options[i].leftExt;
                  }
                }
              }

            }
          }
        } catch (e) {
          ;
        }
        //TODO 被叫叫左话机号
        try {
          //被叫叫左话机号
          if (condition.calledid != '' && condition.calledid != null) {
            if (this.searchForm.calledid.options.length > 0) {
              for (let i = 0; i < this.searchForm.calledid.options.length; i++) {
                if (this.searchForm.calledid.options[i].user_id == condition.calledid) {
                  if (this.searchForm.calledid.options[i].leftExt != undefined) {
                    condition.calledidLeftExt = this.searchForm.calledid.options[i].leftExt;
                  }
                }
              }
            }
          }
        } catch (e) {
          ;
        }
        AuditQuery.queryIpRecord(condition).then((res) => {
          if (res.success) {
            for (var i = 0; i < res.obj.data.length; i++) {

              res.obj.data[i].duration = this.formatSeconds(
                  (res.obj.data[i].endtime - res.obj.data[i].starttime) / 1000);

              res.obj.data[i].starttime = this.GlobalFunc.timeFormatRow(res.obj.data[i].starttime);
              res.obj.data[i].endtime = this.GlobalFunc.timeFormatRow(res.obj.data[i].endtime);
            }
            console.info('%c ' + res.obj.data.length, 'color:red');
            this.tableData = res.obj.data;
            this.total = res.obj.total;
          } else {
            this.$message('获取用户请求错误');
          }
          console.info('%c 获取用户成功' + res, 'color:red');
        }).catch(res => {
          console.info('%c 获取失败', 'color:red');
        });
      },

      /**
       * 查询被叫对讲组
       * */
      queryUser: function() {
        console.info('%c 111233', 'color:red');

        var condition = {
          'fleetId': this.$store.getters.scsFleetId,
        };
        AuditQuery.queryUser(condition).then((res) => {
          if (res.success) {
            var data = res.obj.list;
            data.forEach(function(value) {
              value.subId = value.ID;
            });
            this.searchForm.callerid.options = data;
            this.searchForm.calledid.options = data;
            data.unshift({'NAME': '全部', 'NUMBER': ''});
          } else {
            this.$message('获取用户请求错误');
          }
          console.info('%c 获取用户成功' + res, 'color:red');
        }).catch(res => {
          console.info('%c 获取失败', 'color:red');
        });

      },
      /**
       * 查询被叫对讲组
       * */
      queryGroup: function() {
        var condition = {
          'pageIndex': 1,
          'pageSize': 0,
          'type': 0,
          'fleetId': this.$store.getters.scsFleetId,
          'managePriv': this.$store.getters.managePriv,
          'userId': this.$store.getters.userId,
        };
        AuditQuery.queryGroup(condition).then((res) => {
          if (res.success) {
            var data = res.obj.userInfo;

            data.forEach(function(value) {
              value.NAME = value.name;
              value.NUMBER = value.uid;
            });

            data.push({'NAME': '全部', 'NUMBER': ''});
            this.searchForm.calledid.options = data;
            this.searchForm.groupOptions = data;

          } else {
            this.$message('获取群组请求错误');
          }
          console.info('%c 获取群组成功' + res, 'color:red');
        }).catch(res => {
          console.info('%c 获取失败', 'color:red');
        });

      },
      deal: function(row, value) {

        console.info('%c deal' + row.filepath, 'color:red');
        if (value === 'play') {
          this.showPlayer = false;
          let ipUrl = this.$store.getters.stateBaseUrl1604 + '/' + row.filepath;
          // let ipUrl = "http://192.168.0.209:1604" + '/' + row.filepath;
          this.$nextTick(() => {
            this.videoPlay.src = ipUrl;
            this.videoPlay.title = '录音记录音频';
            this.videoPlay.artist = ' ';
            this.showPlayer = true;
          });
        } else if (value === 'dld') {

          this.handleFileDownland(row.filepath, row.filepath);
        }
      },
      /**
       * 文件下载
       * @param currentUrl
       */
      handleFileDownland(currentUrl, fileName) {
        let ipUrl = this.$store.getters.http + this.$store.getters.stateBaseUrlHostname +
            this.$store.getters.download_port + currentUrl;
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('download', fileName);
        a.href = ipUrl;
        a.click();
        a.parentNode.removeChild(a); // 下载完成移除元素
      },
      /**
       * 处理下载url
       * @param str:字符串
       * @param c处理字符串
       * @param n出现位置
       */
      dealDownloadUrl(str, c, n) {
        let x = str.indexOf(c);
        for (let i = 0; i < n; i++) {
          x = str.indexOf(c, x + 1);
        }
        return x;

      },
      changePageNum: function(val) {
        this.pageNum = val;
        this.query(val);
      },
    },
  };
</script>

<style scoped>
    /deep/ .el-form-item__label {
        font-size: 22px !important;
    }

    /deep/ .el-input__inner {
        font-size: 22px !important;
    }

    .el-table-column--selection .cell {
        padding-right: 1px;
    }

    /*分页修改开始*/
    .el-pagination /deep/ .el-pagination__total {
        font-size: 20px;
        line-height: 60px;
    }

    .el-pagination /deep/ button /deep/ .el-icon .el-icon .el-icon-arrow-left {
        font-size: 50px;
        height: 60px;
        width: 40px;
    }

    /deep/ .el-pager li {
        margin-top: 15px;
        height: 60px;
        width: 60px;
        line-height: 60px;
        font-size: 18px;
    }

    /deep/ .el-pagination.is-background .btn-prev, .el-pager li {
        height: 60px;
        width: 60px;
    }

    /deep/ .el-pagination.is-background .btn-next, .el-pager li {
        height: 60px;
        width: 60px;
    }

    /deep/ .el-pagination .btn-prev .el-icon {
        font-size: 40px;
    }

    /deep/ .el-pagination .btn-next .el-icon {
        font-size: 40px;
    }

    /*分页修改结束*/


    #audioRecord .el-table__body-wrapper {
        overflow-y: auto !important;
    }


    .tableDataClass {
        width: 100%;
        height: 80%;
        text-align: center;
        border-left: 1px solid #EBEBEB;
        font-size: 16px
    }
</style>
